<?php

namespace app\api\service;

use app\common\model\AfterSales;
use app\common\model\Detailed;
use app\common\model\Evaluation;
use app\common\model\Order;
use app\common\model\Parameter;
use app\common\model\Product;
use app\common\model\ShoppingCart;
use app\common\model\User;
use app\common\model\UserAddress;
use app\common\model\UserAmount;
use app\common\service\CommonWechatPayService;
use app\Response;
use think\facade\Db;

class OrderService
{
    private static $order_time_out = 3600;//订单支付超时
    /** 订单列表
     * @param $user_id int 用户ID
     * @param $tid int 抖音号ID
     * @param $page int 页码
     * @param $num int 个数
     * @return string
    */
    public static function orderListService($user_id,$page,$num,$state,$type){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $where[] = ["o.enable","=",1];
        $where[] = ["o.uid","=",$user_id];
        if(is_numeric($state)){
            $where[] = ["o.state","=",$state];
        }
        if(is_numeric($type)){
            $where[] = ["o.type","=",$type];
        }
        $list = Order::orderList($where,$page,$num,"o.*,p.img");
        if(!empty($list)){
            $data = $list->toArray();
            foreach ($data as $k => $v){
                $data[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $count = Order::orderListCount($where);
        }else{
            $data = [];
            $count = 0;
        }
        return Response::wrapData($data,$count);
    }

    /** 下单
     * @param $data array 下单参数
     * @return string
     */
    public static function robOrderService($user_id,$data,$a_id,$address){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $p_info = Product::dataInfo(["id"=>$data["id"]]);
        if(empty($p_info)){
            return Response::wrapError(0,"商品信息异常!");
        }
        if($p_info["state"] != 5){
            return Response::wrapError(0,"商品已下架");
        }
        if($data["num"]>$p_info["inventory"]){
            return Response::wrapError(0,$p_info["p_name"]."库存不足!");
        }
        if($data["type"]==1){
            if(empty($address)){
                $uaInfo = UserAddress::addressInfo(["id"=>$a_id,"uid"=>$user_id]);
                if(empty($uaInfo)){
                    return Response::wrapError(0,"地址信息异常!");
                }
                $address = $uaInfo;
            }
            $stid = 0;
            $s_name = "";
        }else{
            if (empty($address)){
                return Response::wrapError(0,"请设置自提信息");
            }else{
                if(is_string($address)){
                    $address = object_array(json_decode($address));
                }
                $stid = $address["id"];
                $s_name = $address["store_name"];
            }
        }
        if($p_info["commission_price"] > 0){
            if(!empty($userInfo["post_sta_id"])){
                $sta_info = User::userInfo(['uid'=>$userInfo["post_sta_id"]]);
            }
            if(!empty($userInfo["superor_id"])){
                $sup_info = User::userInfo(['uid'=>$userInfo["superor_id"]]);
            }else{
                $sup_info = [];
            }
            $nh_store_delivery_fee = Parameter::parameterValue(["id"=>4]);
            if($data["type"]==2){
                $store_user = User::userInfo(["stid"=>$stid]);
            }else{
                $store_user = [];
            }
            $commission_info = self::commissionInfoCreate($p_info,$sta_info,$sup_info,$data["num"],$nh_store_delivery_fee,$store_user);
        }else{
            $commission_info = [];
        }
        $order_data = [
            "uid" => $user_id,
            "sup_uid" => $userInfo["superor_id"],
            "ps_id" => $userInfo["post_sta_id"],
            "u_type" => $userInfo['type'],
            "type" => $data["type"],
            "p_id" => $data["id"],
            "p_name" => $p_info["p_name"]."-".$p_info["specifications"],
            "p_num" => $p_info["p_num"],
            "sup_price" => $p_info["supply_price"],
            "order_quantity" => $data["num"],
            "stid" => $stid,
            "s_name" => $s_name,
            "com_state" => 1,
            "sup_quantity" => $data["num"],
            "low_price" => bcmul($p_info["supply_price"],$data["num"],2),
            "o_pro_num" => self::genRequestSn($user_id),
            "state" => 0,
            "addtime" => time(),
            "address" => $address,
            "commission_info" => $commission_info
        ];

        Db::startTrans();
        try {
            $id = Order::addInfo($order_data);
            Product::decInfo(["id"=>$data["id"]],"inventory",$data["num"]);
            Product::incInfo(["id"=>$data["id"]],"sold",$data["num"]);
            Db::commit();
            return Response::wrapData($id);
        }catch (\Exception $e){
            Db::rollback();
            return Response::wrapError(0,"下单操作失败");
        }
    }

    /** 微信支付
     * @param $data array 下单参数
     * @return string
     */
    public static function orderWxPayService($id,$user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        if(empty($userInfo["open_id"])){
            return Response::wrapError(-1,"请先授权绑定微信!");
        }
        $oInfo = Order::dataInfo(["id"=>$id,"uid"=>$user_id]);
        if(empty($oInfo)){
            return Response::wrapError(0,"订单信息异常！");
        }
        if($oInfo["state"] > 0){
            return Response::wrapError(0,"该订单不在可支付状态!");
        }
        if($oInfo["state"] == 0&&(time()-$oInfo["addtime"] > self::$order_time_out)){
            Db::startTrans();
            try {
                Order::editInfo(["id"=>$id],["state"=>-1,"remarks"=>"订单支付超时,自动取消!"]);
                Product::incInfo(["id"=>$oInfo["p_id"]],"inventory",$oInfo["order_quantity"]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
            }
            return Response::wrapError(0,"订单已超时,请重新下单!");
        }
        $orderPayInfo = CommonWechatPayService::orderPayData($user_id,$userInfo["open_id"],$oInfo["low_price"],$oInfo["o_pro_num"]);
        if(!empty($orderPayInfo)){
            return Response::wrapData($orderPayInfo);
        }else{
            return Response::wrapError(0,"请稍后重试!");
        }
    }

    /*** 订单详情
     * @param $id int
     * @param $user_id int
     * @return string
     */
    public static function orderInfoService(int $id, int $user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $info = Order::dataInfo(["uid"=>$user_id,"id"=>$id,"enable"=>1]);
        if(empty($info)){
            return Response::wrapError(0,"未检测到当前订单信息!");
        }
        if($info["state"] == 0&&(time()-$info["addtime"] > self::$order_time_out)){
            Db::startTrans();
            try {
                Order::editInfo(["id"=>$id],["state"=>-1,"remarks"=>"订单支付超时,自动取消!"]);
                Product::incInfo(["id"=>$info["p_id"]],"inventory",$info["order_quantity"]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
            }
            return Response::wrapError(0,"订单已超时,请重新下单!");
        }
        $p_info = Product::dataInfo(["id"=>$info["p_id"]]);
        $e_info = Evaluation::dataInfo(["oid"=>$id]);
        if(!empty($p_info)){
            $info["p_info"] = $p_info;
            $info["addtime"] = !empty($info["addtime"])?date("Y-m-d H:i:s",$info["addtime"]):"";
            $info["paytime"] = !empty($info["paytime"])?date("Y-m-d H:i:s",$info["paytime"]):"";
            $info["sendtime"] = !empty($info["sendtime"])?date("Y-m-d H:i:s",$info["sendtime"]):"";
            $info["endtime"] = !empty($info["endtime"])?date("Y-m-d H:i:s",$info["endtime"]):"";
            $info["ev_time"] = !empty($e_info["addtime"])?date("Y-m-d H:i:s",$e_info["addtime"]):"";
        }else{
            $info["p_info"] = [];
        }
        return Response::wrapData($info);
    }

    /*** 订单确认收货
     * @param $id int
     * @param $user_id int
     * @return string
    */
    public static function orderReceiveService($user_id,$id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $info = Order::dataInfo(["uid"=>$user_id,"id"=>$id,"enable"=>1]);
        if(empty($info)){
            return Response::wrapError(0,"未检测到当前订单信息!");
        }
        if($info["state"] != 2){
            return Response::wrapError(0,"订单不在可收货状态!");
        }
        $res = Order::editInfo(["id"=>$id,"uid"=>$user_id],["state"=>3,"endtime"=>time()]);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"操作失败!");
        }
    }

    /***  订单发起评价
     * @param $id int
     * @param $user_id int
     * @param $img_json array
     * @param $content array
     * @return string
    */
    public static function evaluationService($user_id,$id,$img_json,$content){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $info = Order::dataInfo(["uid"=>$user_id,"id"=>$id,"enable"=>1]);
        if(empty($info)){
            return Response::wrapError(0,"未检测到当前订单信息!");
        }
        if($info["state"] != 3){
            return Response::wrapError(0,"订单不在可评价状态!");
        }
        $p_info = Product::dataInfo(["id"=>$info["p_id"]]);
        if($p_info["tie_up_pid"] != 0){
            $p_id = $p_info["tie_up_pid"];
            $sku_id = $info["p_id"];
        }else{
            $p_id = $info["p_id"];
            $sku_id = $info["p_id"];
        }
        $data = [
            "uid" =>$user_id,
            "oid" =>$id,
            "pid" => $p_id,
            "sku_id" => $sku_id,
            "p_name" => $p_info["p_name"],
            "img_json" => $img_json,
            "content" => $content,
            "state" => 1,
            "addtime" => time()
        ];
        Db::startTrans();
        try {
            Evaluation::addInfo($data);
            Order::editInfo(["id"=>$id,"uid"=>$user_id],["state"=>4]);
            Db::commit();
            return Response::wrapData();
        }catch (\Exception $e){
            return Response::wrapError(0,"操作异常");
            Db::rollback();
        }


    }

    /***   购物车下单操作区  ***/
    public static function cartRobOrderCheck($user_id,$cartInfo,$shi_type){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $where[] = ["s.enable","=",1];
        $where[] = ["s.uid","=",$user_id];
        $where[] = ["s.state","=",1];
        $where[] = ["s.id","in",$cartInfo];
        $where[] = ["s.shi_type","=",$shi_type];
        $list = ShoppingCart::shopCartListAll($where);
        if(!empty($list)){
            $list = $list->toArray();
            foreach ($list as $k => $v){
                if($v["num"]>$v["inventory"]){
                    $list[$k]["is_lack"] = 1;//库存不足
                }else{
                    $list[$k]["is_lack"] = 0;//库存正常
                }
                if($v["p_state"] != 5){
                    return Response::wrapError(0,$v["p_name"]."已下架!");
                }
                $list[$k]["subtotal"] = bcmul($v["supply_price"],$v["num"],2);//当前商品小计价格
            }
            $subtotal = array_column($list,"subtotal");
            $sum = array_sum($subtotal);
            return Response::wrapData($list,$sum);
        }else{
            return Response::wrapError(0,"信息异常!");
        }
    }

    public static function cartOrderWxPayService($user_id,$cartInfo,$shi_type,$address,$a_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        if($shi_type==1){
            if(empty($address)){
                $uaInfo = UserAddress::addressInfo(["id"=>$a_id,"uid"=>$user_id]);
                if(empty($uaInfo)){
                    return Response::wrapError(0,"地址信息异常!");
                }
                $address = $uaInfo;
            }
            $stid = 0;
            $s_name = "";
        }else{
            if (empty($address)){
                return Response::wrapError(0,"请设置自提信息");
            }else{
                if(is_string($address)){
                    $address = object_array(json_decode($address));
                }
                $stid = $address["id"];
                $s_name = $address["store_name"];
            }

        }
        $where[] = ["s.enable","=",1];
        $where[] = ["s.uid","=",$user_id];
        $where[] = ["s.state","=",1];
        $where[] = ["s.id","in",$cartInfo];
        $list = ShoppingCart::shopCartListAll($where);
        $sup_info = User::userInfo(['uid'=>$userInfo["superor_id"]]);
        $sta_info = User::userInfo(['uid'=>$userInfo["post_sta_id"]]);
        if($shi_type == 2){
            $store_user = User::userInfo(["stid"=>$stid]);
        }else{
            $store_user = [];
        }
        $order_data=[];
        if(!empty($list)){
            $list = $list->toArray();
            $pay_number = self::createOrderPayNumber();
            $nh_store_delivery_fee = Parameter::parameterValue(["id"=>4]);
            foreach ($list as $k => $v){
                if($v["num"]>$v["inventory"]){
                    return Response::wrapError(0,$v["p_name"]."库存不足!");
                }
                $list[$k]["subtotal"] = bcmul($v["supply_price"],$v["num"],2);//当前商品小计价格
                if($v["commission_price"] > 0){//生成费率、佣金信息
                    $commission_info = self::commissionInfoCreate($v,$sta_info,$sup_info,$v["num"],$nh_store_delivery_fee,$store_user);
                }else{
                    $commission_info = [];
                }
                $order_data[] = [
                    "uid" => $user_id,
                    "sup_uid" => $userInfo["superor_id"],
                    "ps_id" => $userInfo["post_sta_id"],
                    "u_type" => $userInfo['type'],
                    "type" => $v["shi_type"],
                    "p_id" => $v["p_id"],
                    "p_name" => $v["p_name"]."-".$v["specifications"],
                    "p_num" => $v["p_num"],
                    "sup_price" => $v["supply_price"],
                    "order_quantity" => $v["num"],
                    "sup_quantity" => $v["num"],
                    "stid" => $stid,
                    "s_name" => $s_name,
                    "com_state" => 1,
                    "low_price" => bcmul($v["supply_price"],$v["num"],2),
                    "o_pro_num" => self::genRequestSn($user_id),
                    "state" => 0,
                    "addtime" => time(),
                    "address" => $address,
                    "pay_info" => ["out_trade_no"=>$pay_number],
                    "commission_info" => $commission_info
                ];
            }
            $subtotal = array_column($list,"subtotal");
            $sum = array_sum($subtotal);
            Db::startTrans();
            try {
                foreach ($order_data as $k => $v2){
                    Product::decInfo(["id"=>$v2["p_id"]],"inventory",$v2["order_quantity"]);
                    Product::incInfo(["id"=>$v2["p_id"]],"sold",$v2["order_quantity"]);
                }
                $s_where[] = ["uid","=",$user_id];
                $s_where[] = ["state","=",1];
                $s_where[] = ["enable","=",1];
                $s_where[] = ["id","in",$cartInfo];
                ShoppingCart::editInfo($s_where,["state"=>2]);
                Order::addAll($order_data);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
            }
            $orderPayInfo = CommonWechatPayService::orderPayData($user_id,$userInfo["open_id"],$sum,$pay_number,2);
            if(!empty($orderPayInfo)){
                return Response::wrapData($orderPayInfo);
            }else{
                return Response::wrapError(0,"请稍后重试!");
            }
        }else{
            return Response::wrapError(0,"信息异常!");
        }
    }


    /** 分佣json生成
     * @param $p_info array 商品信息
     * @param $sta_info array 上级驿站信息
     * @param $sup_info array 上级团长心意
     * @param $num array 购买数量
     * @param $p_info array $nh_store_delivery_fee 门店配送费用/单价
     * @param $store_user array 门店用户信息
     */
    public static function commissionInfoCreate($p_info,$sta_info,$sup_info,$num,$nh_store_delivery_fee,$store_user){
        if(!empty($sta_info)){
            $sta_commission_rate = $sta_info["commission_rate"]/100;
            $sta_commission_price = 1;
        }else{
            $sta_commission_rate = 0;
            $sta_commission_price = 0;
        }

        if(!empty($sup_info)){
            $sup_commission_rate = $sup_info["commission_rate"]/100;//团长分佣比例
            if($sup_info["commission_rate"] > 85||$sup_info["commission_rate"]==0){
                $sup_commission_rate = 0.85;//团长分佣比例 最高百分之八十五
            }
            $now_commission_price = bcsub($p_info["commission_price"],bcadd($nh_store_delivery_fee,1,2),2);//分佣金额减去（驿站（即公司）分去一元 + 门店固定费用 3元） 剩余可分金额
            $sup_commission_price = bcmul($now_commission_price,$sup_commission_rate,2);
            if(isset($p_info["fs_state"])&&$p_info["fs_state"] == 1){//2024-04-22 新增需求,秒杀专区商品 团长拿6块
                $sup_commission_rate = 0;
                $sup_commission_price = 6;
            }
        }else{
            $now_commission_price = bcsub($p_info["commission_price"],bcadd($nh_store_delivery_fee,1,2),2);
            $sup_commission_rate = 0;
            $sup_commission_price = 0;
        }
        if(!empty($store_user)){
            $store_commission_rate = $store_user["commission_rate"]/100;//门店分佣比例
            if($store_user["commission_rate"] > 15||$store_user["commission_rate"]==0){
                $store_commission_rate = 0.15;//驿站分佣比例
            }
            /** 秒杀专区 门店只拿3元配送 **/
            if(isset($p_info["fs_state"])&&$p_info["fs_state"] == 1){//2024-04-22 新增需求,秒杀专区商品配送门店 固定分3元配送费
                $store_commission_rate = 0;
            }
            /** 秒杀专区 门店只拿3元配送 END **/
            $store_commission_price = bcadd(bcmul($now_commission_price,$store_commission_rate,2),$nh_store_delivery_fee,2);
            $store_uid = $store_user["uid"];
        }else{
            $store_commission_rate = 0;
            $store_commission_price = 0;
            $store_uid = 0;
        }
        $commission_info = [
            "commission_price" => bcmul($p_info["commission_price"],$num,2),//商品总计分佣金额
            "sup_commission_rate" => $sup_commission_rate,
            "sup_commission_price" => bcmul($sup_commission_price,$num,2),
            "sta_commission_rate" => $sta_commission_rate,
            "sta_commission_price" => bcmul($sta_commission_price,$num,2),
            "store_commission_rate" => $store_commission_rate,
            "store_uid" => $store_uid,
            "store_commission_price" =>  bcmul($store_commission_price,$num,2),
            "fs_state" => $p_info["fs_state"],
        ];
        return $commission_info;
    }


    /*** 售后列表
     * @param $user_id int
     * @param $id int
     */
    public static function afterSalesListService($user_id,$page,$num,$state){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $where[] = ["a.enable","=",1];
        $where[] = ["a.uid","=",$user_id];
        if(is_numeric($state)){
            $where[] = ["a.state","=",$state];
        }
        $list = AfterSales::afterSalesList($where,$page,$num);
        if(!empty($list)){
            $list = $list->toArray();
            foreach ($list as $k => $v){
                $list[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $count = AfterSales::afterSalesCount($where);
        }else{
            $list = [];
            $count = 0;
        }
        return Response::wrapData($list,$count);
    }

    /*** 售后详情
     * @param $user_id int
     * @param $id int
    */
    public static function orderAfterSaleService($user_id,$id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23])){
            return Response::wrapError(0,"账户非买家用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $where[] = ["enable","=",1];
        $where[] = ["uid","=",$user_id];
        $where[] = ["oid","=",$id];
        $a_info = AfterSales::dataInfo($where);
        $info = $a_info;
        if(!empty($info)){
            $info["addtime"] = !empty($info["addtime"])?date("Y-m-d H:i:s",$info["addtime"]):"";
        }
        return Response::wrapData($info);
    }

    /** 生成订单号
     * @return bigint
    */
    public static function createOrderNumber(){
        $orderNumber = time().mt_rand(10000,99999);
        $check = Order::dataInfo(["o_pro_num"=>$orderNumber]);
        if(!empty($check)) {
            self::createOrderNumber();
        } else {
            return $orderNumber;
        }
    }


    public static function genRequestSn($unique=0){
        $orderNo = date("YmdHi").substr(microtime(), 2, 7).$unique.mt_rand(10000,99999);
        $check = Order::dataInfo(["o_pro_num"=>$orderNo]);
        if(!empty($check)) {
            self::genRequestSn();
        } else {
            return $orderNo;
        }
    }

    public static function createOrderPayNumber(){
        $orderNumber = time().mt_rand(10000,99999);
        $where[] = ["pay_info->out_trade_no","=",$orderNumber];
        $check = Order::dataInfo($where);
        if(!empty($check)) {
            self::createOrderPayNumber();
        } else {
            return $orderNumber;
        }
    }

}